<template>
  <!-- 搜索栏 -->
  <div class="searchlan-continer">
    <van-pull-refresh
      v-model="refreshing"
      @refresh="onLoad"
      :success-text="isSelectsuccess"
      :success-duration="1000"
    >
      <van-list
        v-model="loading"
        :finished="finished"
        :error.sync="error"
        finished-text="没有更多了"
        error-text="请求失败，点击重新加载"
        @load="onLoad"
      >
        <van-cell v-for="item in list" :key="item.art_id" :title="item.title" />
      </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import { getSearchResult } from "@/api/search.js";
export default {
  data() {
    return {
      list: [],
      //加载
      loading: false,
      // 是否还有
      finished: false,
      //当前页码
      pagenum: 1,
      // 当前文章数量
      pagesize: 20,
      //下拉刷新
      refreshing: false,
      //错误
      error: false,
      // 下拉刷新状态
      isSelectsuccess: "",
    };
  },
  props: ["selectVal"],
  methods: {
    async onLoad() {
      // console.log(this.pagenum);
      // 1 请求
      try {
        const { data: res } = await getSearchResult({
          page: this.pagenum,
          per_page: this.pagesize,
          q: this.selectVal,
        });

        //制造错误  设置加载失败  用来调试
        if (Math.random() > 0.5) {
          // 把 json 转成对象，如果不是  json 就报错，然后下面就可以捕获到了
          // JSON.parse("随机");
        }
        if (this.refreshing) {
          // 2 赋值数据给list
          //下拉刷新放前面
          this.list.unshift(...res.data.results);
          this.refreshing = false;
        } else {
          this.list.push(...res.data.results);
        }
        this.isSelectsuccess = "刷新成功";
        // 3 将本次的loading 关闭
        this.loading = false;

        // 4 判断是否还有 没有就设置为 true 有设置页码+1
        if (res.data.results.length) {
          this.pagenum++;
        } else {
          this.finished = true;
        }
      } catch (err) {
        // this.$toast("获取数据失败");
        console.log(err);
        this.error = true;
        this.loading = false;
        this.refreshing = false;
        this.isSelectsuccess = "刷新失败";
      }
    },
  },
};
</script>

<style>
</style>